<?php
require_once(dirname(__FILE__).'/../config/db_connect.php');
require_once(dirname(__FILE__).'/../employe/employe.cl.php');
require_once(dirname(__FILE__).'/../guardUnit/guardUnit.cl.php');

class Guard {

    private $error = array();
    private $id;
    private $guardUnitId;
    private $employeId;
    private $employeMatricule;
    private $employe;
    private $guardUnit;

    public function __construct() {
        $this->employe = new Employe();
        $this->guardUnit = new GuardUnit();
    }

    public function setValues($data) {

       $this->id =  empty($data['id']) ? '' : strip_tags(trim($data['id']));
       $this->guardUnitId =  empty($data['guard_unit_id']) ? '' : strip_tags(trim($data['guard_unit_id'])); 
       $this->employeId = empty($data['employe_id']) ? '' : strip_tags(trim($data['employe_id']));
       $this->getEmploye()->loadEmployeById($this->getEmployeId());
       $this->employeMatricule = $this->getEmploye()->getMatricule();
       $this->getGuardUnit()->loadGuardUnitById($this->getGuardUnitId());
       
     }
     public function reset() {

       $this->id = '';
       $this->guardUnitId = '';
       $this->employeId = '';
       $this->employeMatricule = '';
       $this->getEmploye()->reset();
       $this->getGuardUnit()->reset();
     }

    public function save($data) {
        
        $this->setValues($data);
        if($this->getId()){
    		if($this->validate()){
    			 $update="UPDATE guard SET guard_unit_id='".$this->guardUnitId."', employe_id ='".$this->employeId."' WHERE id='$this->id' ";
                 mysql_query ($update);
             }
        }			
        else {
        	if ($this->validate()) {
                $this->getEmploye()->loadEmployeByMatricule($this->employeMatricule);
                mysql_query ("INSERT INTO guard VALUES ('','".$this->guardUnitId."','".$this->getEmploye()->getId()."')");
                $this->reset();
                //return $this->getguard(mysql_insert_id());
            }
        }
    }

    public function loadGuardByID($id) {
        
        $select = "SELECT * FROM guard WHERE id = '$id'";
        $resource = mysql_query($select);
        $this->setValues(mysql_fetch_assoc($resource));
    }

    public function getAllGuards() {
        
        $select = "SELECT * FROM guard ";
        $resource = mysql_query($select);
	    	$guards = array();
        while($guard = mysql_fetch_object($resource)) {
        	  $guards[] = $guard;
        } 
        return $guards; 
    }    

    private function validate() {

        if (empty($this->guardUnitId)) {
             $this->addError("guard_unit_id","Saisissez l'Id d'une unité de garde");
        }
        if (empty($this->employeMatricule)) {
             $this->addError("employeMatricule","Saisissez le matricule d'un employe");
        }
            if(count($this->error) > 0) {
            return false;
        } else {
            return true;
        }      
    }

   private function addError($index, $error) {
        $this->error[$index] =  $error;
    }

    public function getError($index) { 
      if(!empty($this->error[$index])) {
        return '<div class="alert alert-error">'.$this->error[$index].'</div>';
      }
    }
    public function hasError() {
       return count($this->error) > 0 ? true : false;
    }
    public function getGuardUnitId(){
    	return $this->guardUnitId;
    }    
    public function getEmployeId(){
    	return $this->employeId;
    }
    public function getId(){
        return $this->id;
    }
    public function getEmployeMatricule(){
        return $this->employeMatricule;
    }
    public function getEmploye(){
        return $this->employe;
    }
    public function getGuardUnit(){
        return $this->guardUnit;
    }

    public function insert($employeId, $unitId) {

        $select = "SELECT * FROM guard WHERE guard_unit_id='$unitId' AND employe_id='$employeId'";
        if(mysql_num_rows(mysql_query($select)) == 0) {  
            $sql = "INSERT INTO guard VALUES('', '$unitId', '$employeId')";
            //echo $sql.'<br>';
            mysql_query($sql);
        }
    }

   public function generateGuards() {


       $guardTypeEmployeType = array(array('guardType'=>" type<>'".GuardUnit::WEEK."'", 'employeType'=>Employe::ENGINEER),
                                     array('guardType'=>" type='".GuardUnit::WEEK."'", 'employeType'=>Employe::AGENT));
 
       foreach($guardTypeEmployeType as $guardEmploye) {

           $guardUnits = $this->getGuardUnit()->getAllGuardUnitsWhereType($guardEmploye['guardType']);
           $services = $this->getEmploye()->getService()->getAllServices();

           foreach($services as $service) {

             $employes = $this->getEmploye()->getEmployesByServiceIdAndType($service->id, $guardEmploye['employeType']);

             $i=0;
             $reset = count($employes);
             if($reset == 0) {
                 continue;
             }
             foreach($guardUnits as $unit) {
                if($reset == $i) {
                    $i = 0;
                }
                //echo($employes[$i]->id.' ----- '.$employes[$i++]->service_id.' ---- '. $unit->id).'<br />';
                $this->insert($employes[$i++]->id, $unit->id);   
             }
          }
      }
   }

   public function getGuardByServiceAndTypeAndDate($serviceId, $type='', $date=array()) {

       $select = "SELECT *, guard.id as id, employe.type as post, guard_unit.label as unit_label, service.name as service_name, guard_unit.type as unit_type FROM guard JOIN employe on employe.id = guard.employe_id JOIN guard_unit on guard_unit.id = guard.guard_unit_id JOIN service on employe.service_id=service.id";
       $select .= " WHERE employe.service_id = '$serviceId'";
       $select .= $type <> ''  ? " AND (employe.type='$type')" : '';
       $select .= !empty($date['start_date']) ? ' AND (guard_unit.start_date >= \''.$date['start_date'].'\')' : '';
       $select .= !empty($date['end_date']) ? ' AND (guard_unit.end_date <= \''.$date['end_date'].'\')' : '';  
  
       $resource = mysql_query($select);

        $guards = array();
        while($guard = mysql_fetch_object($resource)) {
              $guards[$guard->post][] = $guard;
        }
        return $guards;   
   }
   
   public function guardExist() {

       $select = "SELECT count(*) as total FROM guard JOIN employe on employe.id = guard.employe_id JOIN guard_unit on guard_unit.id = guard.guard_unit_id";
       $select .= ' WHERE (guard_unit.start_date >= \''.date('Y').'-01-01\')';
       $total = mysql_fetch_object(mysql_query($select));
       return $total->total > 0 ? true :false;
   }
}

